﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.SessionState;
using System.Security.Principal;
using System.Configuration;

namespace LenderClearingHouse
{
  public class Global : System.Web.HttpApplication
  {

    void Application_Start(object sender, EventArgs e)
    {
      // Code that runs on application startup

    }

    void Application_End(object sender, EventArgs e)
    {
      //  Code that runs on application shutdown

    }

    void Application_Error(object sender, EventArgs e)
    {
        if (!string.IsNullOrEmpty(ConfigurationManager.AppSettings["IsDevelopmentEnvironment"])) return;

        System.Exception ex = Server.GetLastError();
        try
        {            
            User usr = Session["User"] as User;
            DataAccess da = new DataAccess();
            da.ExecuteSQLNonQuery(string.Format(@"insert into Log([EventMessage], [StackTrace], [CurrentUser], [Path], [QueryString], [Browser], [UserHostAddress], [UrlReferrer])
                values('{0}', '{1}', '{2}', '{3}', '{4}', '{5}', '{6}', '{7}')",
                (ex.InnerException != null ? ex.InnerException.Message : ex.Message).Replace("'", "''"),
                (ex.InnerException != null ? ex.InnerException.StackTrace : ex.StackTrace).Replace("'", "''"),
                usr != null ? usr.UserName : "",
                Context.Request.Path.Replace("'", "''"),
                Context.Request.QueryString.ToString(),
                Context.Request.Browser.Browser,
                Context.Request.UserHostAddress,
                (Context.Request.UrlReferrer != null ? Context.Request.UrlReferrer.ToString() : "")
            ));

            Response.Write("Unexpected error occurs. See log for details");
            Server.ClearError();
        }
        catch(Exception exNew)
        {
            Response.Write("Unexpected error occurs (" + ex.Message + " -> " + exNew.Message + ")<br/>" + ex.StackTrace);
            Server.ClearError();
        }
    }

    void Session_Start(object sender, EventArgs e)
    {
      // Code that runs when a new session is started

    }

    void Session_End(object sender, EventArgs e)
    {
      // Code that runs when a session ends. 
      // Note: The Session_End event is raised only when the sessionstate mode
      // is set to InProc in the Web.config file. If session mode is set to StateServer 
      // or SQLServer, the event is not raised.

    }

    protected void Application_AuthenticateRequest(Object sender, EventArgs e)
    {
      //if (HttpContext.Current.User != null)
      //{
      //  if (HttpContext.Current.User.Identity.IsAuthenticated)
      //  {
      //    if (HttpContext.Current.User.Identity is FormsIdentity)
      //    {
      //      FormsIdentity id = (FormsIdentity)HttpContext.Current.User.Identity;
      //      FormsAuthenticationTicket ticket = id.Ticket;
      //      string userInfo = ticket.UserData;
      //      string[] roles = userInfo.Split(',');
      //      HttpContext.Current.User = new GenericPrincipal(id, roles);
      //    }
      //  }
      //}
    }
  }
}
